import React, { useEffect, useState } from "react";
import { Layout, Menu, Button, Space, message } from "antd";
import {
  UserOutlined,
  ProjectOutlined,
  FileTextOutlined,
  RobotOutlined,
  AndroidOutlined
} from "@ant-design/icons";
import { history, useLocation, Outlet } from "umi";
import styles from "./BasicLayout.less";
import { auth } from "@/utils/auth";
const { Header, Sider, Content } = Layout;

/*************  ✨ Windsurf Command ⭐  *************/
/**
 * BasicLayout component serves as the main layout for the application.
/*******  c5875535-1769-4fe8-b73f-8df991a4bed8  *******/const BasicLayout: React.FC = () => {
  const location = useLocation();
  const [username, setUsername] = useState<string>("");
  const [collapsed, setCollapsed] = useState(true);

  React.useEffect(() => {
    // 检查用户是否已登录
    if (!auth.isLoggedIn()) {
      message.error("请先登录");
      history.push("/login");
      return;
    }

    setUsername(auth.getUsername() || "");
  }, [location.pathname]); // 当路由变化时重新检查

  const handleLogout = async () => {
    try {
      // 调用登出API
      const response = await fetch("/agentapi/auth/logout", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      });

      // 无论API响应如何，都清除本地令牌
      auth.clearTokens();
      message.success("已退出登录");
      history.push("/login");
    } catch (error) {
      // 发生错误时也清除本地令牌
      auth.clearTokens();
      message.success("已退出登录");
      history.push("/login");
    }
  };

  const menuItems = [
    {
      key: "/users",
      icon: <UserOutlined />,
      label: "用户管理",
    },
    {
      key: "/t_device_mange",
      icon: <AndroidOutlined />,
      label: "设备管理",
    },
    {
      key: "/tasks",
      icon: <ProjectOutlined />,
      label: "任务管理",
    },
    {
      key: "/contents",
      icon: <FileTextOutlined />,
      label: "文案管理",
    },
  ];

  return (
    <Layout style={{ minHeight: "100vh", margin: 0, border: "0px solid red" }}>
      <Header className={styles.header}>
        <div className={styles.logo}>AI分身管理系统</div>
        <Space>
          <Button type="link" onClick={() => history.push("/aitest")}>
            <RobotOutlined />
            AI效果体验
          </Button>
          <span>{username}</span>
          <Button type="link" onClick={handleLogout}>
            退出登录
          </Button>
        </Space>
      </Header>
      <Layout>
        <Sider
          width={200}
          theme="light"
          collapsible
          collapsed={collapsed}
          onCollapse={(value) => setCollapsed(value)}
          className={styles.sider}
        >
          <Menu
            mode="inline"
            selectedKeys={[location.pathname]}
            items={menuItems}
            onClick={({ key }) => history.push(key)}
            className={styles.menu}
          />
        </Sider>
        <Layout style={{ padding: "24px" }}>
          <Content className={styles.content}>
            <Outlet />
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default BasicLayout;
